package com.lihainuo.springai.redis.strater;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;

import java.io.Serializable;
import java.util.Map;

/**
 * 可序列化的 Message 包装类
 */
@Getter
public class SerializableMessage implements Serializable {
    // 定义序列化版本号, 用于版本控制
    private static final long serialVersionUID = 1L;

    // 明确 Message 接口实现类的枚举
    public enum MessageType { USER, ASSISTANT, SYSTEM }

    private final MessageType messageType;
    private final String textContent;
    private final Map<String, Object> metadata;

    public SerializableMessage(Message message) {
        this.messageType = getMessageType(message);
        this.textContent = message.getText();
        this.metadata = message.getMetadata();
    }

    // 判断属于哪种具体的实现类的类型
    private MessageType getMessageType(Message message) {
        if (message instanceof SystemMessage) return MessageType.SYSTEM;
        if (message instanceof UserMessage) return MessageType.USER;
        if (message instanceof AssistantMessage) return MessageType.ASSISTANT;
        throw new IllegalArgumentException("Unknown message type: " + message.getClass().getName());
    }

    // 将 SerializableMessage 转换为 Message
    public Message toMessage() {
        switch (messageType) {
            case SYSTEM:
                return new SystemMessage(textContent);
            case ASSISTANT:
                return new AssistantMessage(textContent, metadata);
            case USER:
                return new UserMessage(textContent);
            default:
                throw new IllegalArgumentException("Unknown message type: " + messageType);
        }
    }

    @JsonCreator
    public SerializableMessage (
            @JsonProperty("messageType") MessageType messageType,
            @JsonProperty("textContent") String textContent,
            @JsonProperty("metadata") Map<String, Object> metadata
    ) {
        this.messageType = messageType;
        this.textContent = textContent;
        this.metadata = metadata;
    }

}
